package com.api.demo.service.impl;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.api.demo.entity.ApiLog;
import com.api.demo.entity.SlowLog;
import com.api.demo.mapper.ApiLogMapper;
import com.api.demo.mapper.SlowLogMapper;
import com.api.demo.service.ApiLogService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class ApiLogServiceImpl implements ApiLogService {

    @Resource
    private ApiLogMapper apiLogMapper;

    @Resource
    private SlowLogMapper slowLogMapper;

    private static final Logger logger = LoggerFactory.getLogger(ApiLogServiceImpl.class);

    @Value("${slowlog.threshold:1000}") // 改为可配置
    private long slowLogThreshold;

    // 异步写入日志
    @Async("logTaskExecutor")
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void logAsync(ApiLog log) {
        try {
            if (log == null)
                return;
            apiLogMapper.insert(log);

            // 慢日志处理（阈值1秒）
            if (log.getDuration() > slowLogThreshold) {
                try {
                    SlowLog slowLog = new SlowLog();
                    slowLog.setLogId(log.getId());
                    slowLog.setPath(log.getPath());
                    slowLog.setDuration(log.getDuration());
                    slowLogMapper.insert(slowLog);
                } catch (Exception e) {
                    logger.error("Slow log save failed", e);
                }
            }
        } catch (Exception e) {
            // 日志写入失败处理
            logger.error("Log saving failed: {}", e.getMessage());

            // 可选：写入本地文件作为备份
            writeToLocalFile(log);
        }
    }

    private void writeToLocalFile(ApiLog log) {
        // 实现日志写入本地文件的方法
    }

    @Override
    public TaskExecutor logTaskExecutor() {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException("Unimplemented method 'logTaskExecutor'");
    }
}
